package com.redpacketcover.rc.tabbar;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.redpacketcover.rc.MainActivity;
import com.redpacketcover.rc.R;
import com.redpacketcover.rc.base.BaseResponseBean;
import com.redpacketcover.rc.base.RetrofitManager;
import com.redpacketcover.rc.base.ObserverCallback;
import com.redpacketcover.rc.bean.GoodsRecord;
import com.redpacketcover.rc.goods.GoodsApiService;
import com.redpacketcover.rc.adapter.GoodsListAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class TabGoodsFragment extends Fragment {

    private Context context;
    private Activity activity;
    private FragmentManager sFragmentManager;

    private GoodsListAdapter mgoodslist;

    private List<GoodsRecord> mList = new ArrayList<>();

    private int page = 1; //页数
    private int pageSize = 20; //每页条数
    private int total = 0; //总条数

    private Boolean isPullRefresh = false; // 是否下拉刷新状态

    private GridView grid_photo;
    private SmartRefreshLayout refreshLayout;

    public TabGoodsFragment(FragmentManager supportFragmentManager, MainActivity mainActivity) {
        super();
        this.activity = mainActivity;
        this.sFragmentManager = supportFragmentManager;
        this.context = mainActivity.getApplicationContext();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.goods_list_layout,container,false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        grid_photo = view.findViewById(R.id.grid_photo);
        refreshLayout = view.findViewById(R.id.refreshLayout);
//        initData();
        setListener();
    }


    private void setListener() {
        mgoodslist = new GoodsListAdapter(context);
        grid_photo.setAdapter(mgoodslist);
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.resetNoMoreData(); //恢复没有更多
                page = 1;
                isPullRefresh = true;
                initData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isPullRefresh = false;
                page++;
                initData();
            }
        });
    }

    private void initData() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("page",page);
        params.put("pageSize",pageSize);
        GoodsApiService service = RetrofitManager.getInstance().create(GoodsApiService.class);
        Observable<BaseResponseBean<List<GoodsRecord>>> observable = service.getGoodsList(params);
        DisposableObserver observer = new ObserverCallback<List<GoodsRecord>>() {

            @Override
            public void onSuccess(List<GoodsRecord> model) throws ParseException {
                if (isPullRefresh) {
                    mgoodslist.clear();
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                }
                try {
                    List<GoodsRecord> list = new ArrayList<>();
                        for(int i=0;i<model.size();i++){
                            list.add(model.get(i));
                        }

                            total = model.size();
                    if (mList == null) mList = null;
                    if (page == 1) {
                        if(mList != null){
                            mList.clear();
                        }
                    }
                    mList.addAll(list);
                    mgoodslist.setData(mList);
                    mgoodslist.notifyDataSetChanged();
                    isPullRefresh = false;
                } catch (Exception e) {
                    Log.d("2222",""+e);
                }
            }

            @Override
            public void onFailure(int code, String errMsg) {

            }
        };
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
